package com.flywolf.mooncalendar2013;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
import java.util.StringTokenizer;

import android.content.res.Resources;
import android.util.Log;

public class MoonDataArray {
	HashMap<Date, MoonData> data;
	protected Set<Integer> badDays;
	protected Set<Integer> goodDays;
	protected Set<Integer> manWomen;
	protected Set<Integer> manWomenNot;
	protected Set<Integer> shower;
	protected Set<Integer> showerNot;
	protected Set<Integer> clear;
	protected Set<Integer> haircut;
	protected Set<Integer> haircutNot;
	final String LOG_TAG = "myLogs";
	protected HashMap<Integer, String> dateNames;
	String tag = "";
	Date date;

	MoonDataArray() {
		init();
	}

	public int checkGrowId(MoonData current)

	{
		int res = 0;
		if (current.getMoonFase().contentEquals("newmoon")
				&& (current.getSign().contentEquals("scorpio")
						|| current.getSign().contentEquals("pisces") || current
						.getSign().contentEquals("cancer"))) {
			res = R.drawable.growsalat;
			tag = "growsalat";
		}
		if (current.getMoonFase().contentEquals("newmoon")
				&& (current.getSign().contentEquals("gemini")
						|| current.getSign().contentEquals("libra") || current
						.getSign().contentEquals("aquarius"))) {
			res = R.drawable.growflower;
			tag = "growflower";
		}
		if (current.getMoonFase().contentEquals("newmoon")
				&& (current.getSign().contentEquals("aries")
						|| current.getSign().contentEquals("leo") || current
						.getSign().contentEquals("sagittarius"))) {
			res = R.drawable.growtomato;
			tag = "growtomato";
		}
		if (current.getMoonFase().contentEquals("wanningmoon")
				&& (current.getSign().contentEquals("taurus")
						|| current.getSign().contentEquals("virgo") || current
						.getSign().contentEquals("capricorn"))) {
			res = R.drawable.growpotato;
			tag = "growpotato";
		}
		return res;
	}

	public int checkFood(MoonData current)

	{
		int res = 0;
		if ((current.getSign().contentEquals("scorpio")
				|| current.getSign().contentEquals("pisces") || current
				.getSign().contentEquals("cancer"))) {
			res = R.drawable.carbohydrates;
			tag = "carbohydrates";
		}
		if ((current.getSign().contentEquals("gemini")
				|| current.getSign().contentEquals("libra") || current
				.getSign().contentEquals("aquarius"))) {
			res = R.drawable.fats;
			tag = "fats";
		}
		if ((current.getSign().contentEquals("aries")
				|| current.getSign().contentEquals("leo") || current.getSign()
				.contentEquals("sagittarius"))) {
			res = R.drawable.proteins;
			tag = "proteins";
		}
		if ((current.getSign().contentEquals("taurus")
				|| current.getSign().contentEquals("virgo") || current
				.getSign().contentEquals("capricorn"))) {
			res = R.drawable.salt;
			tag = "salt";
		}

		return res;
	}

	/*
	 * public int checkBody(MoonData current)
	 * 
	 * { int res = 0; if (current.getSign().contentEquals("aries")) res =
	 * R.drawable.aries_body; if (current.getSign().contentEquals("taurus")) res
	 * = R.drawable.taurus_body; if (current.getSign().contentEquals("gemini"))
	 * res = R.drawable.gemini_body; if
	 * (current.getSign().contentEquals("cancer")) res = R.drawable.cancer_body;
	 * tag="";
	 * 
	 * return res; }
	 */
	
	public MoonData getDayByDate(Date inDate) {
		MoonData m=null;
		DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
		try {
			date=inDate;
			m=data.get(dateFormat.parse(dateFormat.format(inDate)));
			if (!compareDates(inDate,m.getMoonRise()))
			{
				Log.d(LOG_TAG, "heyaaaaaaaa not compare"+m.getMoonDay());
				date=addDays(inDate,-1);
				m=data.get(dateFormat.parse(dateFormat.format(date)));
				
				Log.d(LOG_TAG, "heyaaaaaaaa not compare!"+m.getMoonDay());
			}
			
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return m; 
	}
	   public Date getDate() {
		return date;
	}

	public void setDate(Date date) {
		this.date = date;
	}

	public static Date addDays(Date date, int days)
	    {
	        Calendar cal = Calendar.getInstance();
	        cal.setTime(date);
	        cal.add(Calendar.DATE, days); //minus number would decrement the days
	        return cal.getTime();
	    }	
	public boolean compareDates(Date date,String time) {
        String res = "";
        Date dateWithRise=null;
        if (date != null) {
            try {
            SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd");
            StringBuilder nowYYYYMMDD = new StringBuilder(dateformat.format(date));
            res = nowYYYYMMDD.toString()+" "+time;
            DateFormat formatter;
           // Date date;
            formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            formatter.setLenient(false);
            dateWithRise = (Date) formatter.parse(res);
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			Log.d(LOG_TAG, "heyaaaaaaaa222!!"+date + " "+ res+" ");

        }
		long diff = (dateWithRise.getTime()+(24 * 60 * 60 * 1000)) - date.getTime();
		if (diff > 0 && diff < 24 * 60 * 60 * 1000) {
			return true;
		} else {
			return false;
		}
	}
	
	
	public void readCsv(Resources res) {
		// List<ImportedXls> datalist = new ArrayList<ImportedXls>();
		data = new HashMap<Date, MoonData>();
		try {
			// Resources res = getResources();
			InputStream in_s = res.openRawResource(R.raw.moondata);

			BufferedReader reader = new BufferedReader(new InputStreamReader(
					in_s));
			String line = reader.readLine();
			line = reader.readLine();
			while (line != null) {
				StringTokenizer st = new StringTokenizer(line, ";");

				String dateStr = st.nextToken();
				Date date = stringToDate(dateStr);
				int moonDay = Integer.parseInt(st.nextToken()
						.replaceAll("\\s", "").replaceAll(",", "0"));
			//	Log.d(LOG_TAG,dateStr+"moonDaySet="+ moonDay);
				// в Т st.nextToken();
				String moonRise = st.nextToken().replaceAll("\\s", "");
				try {
					if (!moonRise.contentEquals(""))
						date = stringToDate(dateStr + " " + moonRise);
				} catch (Exception ex) {
					Log.d(LOG_TAG, "cant parce date with time");

				}

				// Log.d(LOG_TAG,"moonDay="+ moonDay+";"+
				// moonDay.replaceAll("\\s", "")+".");
				// st.nextToken();
				st.nextToken();
				String sign = st.nextToken().replaceAll("\\s", "")
						.toLowerCase();
				st.nextToken();
				String moonFase = st.nextToken().replaceAll("\\s", "")
						.toLowerCase();

				/** PROBLEM */
				// String index = st.nextToken();
				/** PROBLEM */

				MoonData temp = new MoonData();
				temp.setMoonDay(moonDay);
				temp.setMoonRise(moonRise);
				temp.setSign(sign.trim());
				temp.setMoonFase(moonFase.trim());
				// Log.d(LOG_TAG,"date="+ date);
				data.put(date, temp);

				// read the next line
				// txt.setText(new String(line));
				// Log.d(LOG_TAG, line);
				line = reader.readLine();
			}
			// byte[] b = new byte[in_s.available()];
			// in_s.read(b);
			// txt.setText(new String(b));
		} catch (Exception e) {
			// e.printStackTrace();
			Log.d(LOG_TAG, ": can't show help.");
			// txtHelp.setText("Error: can't show help.");
		}

	}

	public static Date stringToDate(String strDate) {

		try {
			DateFormat formatter;
			Date date;
			formatter = new SimpleDateFormat("dd/MM/yyyy");
			date = (Date) formatter.parse(strDate);
			return date;
		} catch (Exception e) {
			Log.e("log_tag", e.toString());
			return null;
		}
	}
	public static Date stringToDateTime(String strDate) {

		try {
			DateFormat formatter;
			Date date;
			formatter = new SimpleDateFormat("dd/MM/yyyy HH:mm");
			date = (Date) formatter.parse(strDate);
			return date;
		} catch (Exception e) {
			Log.e("log_tag", e.toString());
			return null;
		}
	}

	private void init()

	{
		dateNames = new HashMap<Integer, String>();
		dateNames.put(1, "светильник");
		dateNames.put(2, "рог изобилия");
		dateNames.put(3, "леопард");
		dateNames.put(4, "райское дерево");
		dateNames.put(5, "единорог");
		dateNames.put(6, "птица");
		dateNames.put(7, "роза ветров");
		dateNames.put(8, "пожар");
		dateNames.put(9, "летучая мышь");
		dateNames.put(10, "фонтан");
		dateNames.put(11, "корона");
		dateNames.put(12, "сердце");
		dateNames.put(13, "кольцо");
		dateNames.put(14, "труба");
		dateNames.put(15, "змей");
		dateNames.put(16, "голубь");
		dateNames.put(17, "гроздь винограда");
		dateNames.put(18, "зеркало");
		dateNames.put(19, "паук");
		dateNames.put(20, "орёл");
		dateNames.put(21, "конь");
		dateNames.put(22, "слон");
		dateNames.put(23, "крокодил");
		dateNames.put(24, "медведь");
		dateNames.put(25, "черепаха");
		dateNames.put(26, "жаба");
		dateNames.put(27, "трезубец");
		dateNames.put(28, "лотос");
		dateNames.put(29, "спрут");
		dateNames.put(30, "золотой лебедь");
		dateNames.put(291, "спрут, светильник");
		dateNames.put(301, "золотой лебедь, светильник");
		dateNames.put(102, "светильник, рог изобилия");
		badDays = new HashSet<Integer>();
		badDays.add(9);
		badDays.add(15);
		badDays.add(19);
		badDays.add(26);
		badDays.add(29);
		goodDays = new HashSet<Integer>();
		goodDays.add(1);
		goodDays.add(13);
		goodDays.add(14);
		goodDays.add(17);
		goodDays.add(22);
		goodDays.add(28);
		manWomen = new HashSet<Integer>();
		manWomen.add(1);
		manWomen.add(2);
		manWomen.add(6);
		manWomen.add(11);
		manWomen.add(17);
		manWomen.add(21);
		manWomenNot = new HashSet<Integer>();
		manWomenNot.add(9);
		manWomenNot.add(13);
		manWomenNot.add(15);
		manWomenNot.add(19);
		manWomenNot.add(23);
		manWomenNot.add(26);
		shower = new HashSet<Integer>();
		shower.add(13);
		shower.add(28);
		shower.add(25);
		showerNot = new HashSet<Integer>();
		showerNot.add(8);
		// showerNot.add(27);
		clear = new HashSet<Integer>();
		clear.add(7);
		clear.add(9);
		clear.add(16);
		clear.add(20);
		clear.add(28);
		haircut = new HashSet<Integer>();
		haircut.add(14);
		haircut.add(16);
		haircut.add(17);
		haircutNot = new HashSet<Integer>();
		haircutNot.add(9);
		haircutNot.add(15);
		haircutNot.add(23);
		haircutNot.add(29);
	}
}
